const express = require("express");
const router = express.Router();
const UsersModel = require("../db/modules/users");
const md5 = require('md5')
router.get("/reg", function (req, res) {
  res.render("auth/reg");
});
router.get("/login", function (req, res) {
  res.render("auth/login");
});
router.post("/reg", function (req, res) {
  req.body.password = md5(req.body.password)
  UsersModel.create(req.body)
    .then((result) => {
      res.render('success',{tips:'注册成功',url:'/login'})
    })
    .catch((error) => {
      res.json({
        code: 500,
        msg: "操作失败",
        data: error,
      });
    });
});
router.post("/login", function (req, res) {
  UsersModel.findOne({userName:req.body.username}).then((result) => {
    if (!result) {
      return res.send('账号不存在，请先注册')
    }
    UsersModel.findOne({password:md5(req.body.password)}).then((result) => {
      if (!result) {
        return res.send('密码错误')
      }
      req.session.userName = result.userName
      req.session._id = result._id
      res.render('success',{tips:'登录成功',url:'/list'})
    })
    .catch((error) => {
      res.json({
        code: 500,
        msg: "操作失败",
        data: error,
      });
    });
  })
  .catch((error) => {
    res.json({
      code: 500,
      msg: "操作失败",
      data: error,
    });
  });
});
router.post("/logout", function (req, res) {
  req.session.destroy(() => {
    res.render('success',{tips:'退出成功',url:'/login'})
  })
});
module.exports = router;
